var audio = document.getElementById('audio-player');
const [stageWidth, stageHeight] = [window.innerWidth, window.innerHeight];
var canvas=document.getElementById('canvas');
[canvas.width,  canvas.height]=[stageWidth,stageHeight];
const stage = createui.initStage(canvas,onLoop);

var [cx,cy]=[stageWidth/2,stageHeight/2];

let src=""
var image=new MImage({url:src,isCenter:true});
stage.addChild(image);
image.setPos(cx,cx);
src="../rec/control/center.png"
let imgCenter=new MImage({url:src,isCenter:true});
stage.addChild(imgCenter);
imgCenter.setPos(cx,cx);

var labelName=new MLabel({label:'歌曲'});
labelName.fontSize=50;
labelName.color='#ffffff'
labelName.setPos(cx,cy*1.1);
stage.addChild(labelName);

var labelLyrics=new MLabel({label:'歌词'});
labelLyrics.fontSize=40;
labelLyrics.color='#ffffff'
labelLyrics.setPos(cx,cy*1.3);
stage.addChild(labelLyrics);

var labelTime=new MLabel({label:'时间'});
labelTime.fontSize=40;
labelTime.setPos(cx,cy*1.85);
stage.addChild(labelTime);

var bgX=100;
var bgW=stageWidth-bgX*2;
var bar=new MSprite();
bar.dc(10,'white');
bar.setPos(bgX,cy*1.8);
stage.addChild(bar);
var bgProgress=new MSprite();
bgProgress.dr(bgW,60,'white');
bgProgress.setPos(bgX,cy*1.8-30);
bgProgress.alpha=0.1;
bgProgress.addEvent('click',onProgress);
bgProgress.scaleX=0;
stage.addChild(bgProgress);
var bagBg=new MSprite();
bagBg.dr(bgW,4,'white');
bagBg.setPos(bgX,cy*1.8-2);
stage.addChild(bagBg);

var lyValue;
var soundSrc;
var lyrics;
var currentTime=0;
var btnPlay,btnStop,btnPrev,btnNext;
var names=['conPlay','conStop','conPrev','conNext'];
for(let i=0;i<names.length;i++){
	let name=names[i];
	let src=`../rec/control/${name}.png`;
	let image=new MImage({url:src,isCenter:true});
	stage.addChild(image);
	image.setPos(cx,stageHeight*0.8);
	image.addEvent('click',onControl);
	image.name=name;
	switch(i){
		case 0: btnPlay=image;                    break;
		case 1: btnStop=image;                    break;
		case 2: btnPrev=image;   image.setPos(cx-160);     break;
		case 3: btnNext=image;   image.setPos(cx+160);     break;
	}
}
btnStop.visible=false;
var index=0;
var total=jsonDatas.length-1;
function onControl(e){
	var target=e.currentTarget;
	MTween.set(target).go(100,{scale:0.8}).go(100,{scale:1}).start();
	var name=target.name;
	console.log(name);
	switch(name){
		case 'conPlay':
			if(audio.src!=soundSrc)audio.src=soundSrc;
			//console.log('audio',audio,audio.src,soundSrc)
			audio.currentTime=currentTime;
			audio.play();
			btnPlay.visible=false;
			btnStop.visible=true;
			break;
		case 'conStop':
			audio.pause();
			btnPlay.visible=true;
			btnStop.visible=false;
			break;
		case 'conPrev':
			index--;
			index=index<=0?0:index;
			selectSound();
			break;
		case 'conNext':
			index++;
			index=index>=jsonDatas.length?0:index;
			selectSound();
			break;
	}
}
// 更新歌词
function updateLyrics(currentTime) {
	//console.log(currentTime)
	if(!lyrics)return;
	for (var i = 0; i < lyrics.length; i++) {
		if (currentTime >= lyrics[i].time && (!lyrics[i + 1] || currentTime < lyrics[i + 1].time)) {
			lyValue=lyrics[i].text;
			if(lyValue!=labelLyrics.value){
				MTween.set(labelLyrics).go(0,{alpha:0}).go(500,{alpha:1}).start();
			}
			labelLyrics.value = lyValue;
			break;
		}
	}
	
}

// 监听频播放时间更新事件
audio.addEventListener('timeupdate', function() {
	currentTime = audio.currentTime;
	var totalTime=audio.duration;
	if(currentTime<totalTime){
		bar.x=bgX+currentTime/totalTime*bgW;
		labelTime.value=TimeFactory.formatTime(currentTime)+'/'+TimeFactory.formatTime(totalTime);
		updateLyrics(currentTime);
	}else if(currentTime>=totalTime){
		onControl({currentTarget:{name:'conNext'}})
	}
});

// 监听频播放时间更新事件
audio.addEventListener('progress', function() {
	const buffered = audio.buffered;
	if (buffered.length > 0) {
		const loadedPercentage = (buffered.end(0) / audio.duration);
		bgProgress.scaleX=loadedPercentage;
		console.log(loadedPercentage)
	}
});
function onProgress(e){
	var x=e.stageX-bgProgress.x;
	var p=x/bgProgress.width;
	audio.currentTime=p*audio.duration;
}
function onLoop(){
	if(image){
		if(btnStop.visible)image.rotation+=1;
	}
}
function selectSound(isPlay=true){
	let data=jsonDatas[index];
	soundSrc=data.src;
	lyrics=data.lyrics;
	currentTime=0;
	labelName.value=data.name;
	imgCenter.visible=!!data.cdIcon;
	if(data.cdIcon)image.setSrc(data.cdIcon);
	//console.log(soundSrc,lyrics)
	isPlay&&onControl({currentTarget:{name:'conPlay'}})
}
selectSound(false);
//如http://ywx.com?select=0,1,2?color=black
function getUrlVar(name){

	// 首先，创建一个新的URL对象
	const url = new URL(window.location.href);
	// 然后，使用URLSearchParams来获取所有的查询参数
	const params = new URLSearchParams(url.search);
	// 获取特定的查询参数
	const value = params.get(name); // 返回 'value'
	return value;
}

var nums=getUrlVar('select');
if(nums){
	nums=nums.split(',');
	var arr=[];
	nums.forEach(i => {
		arr.push(jsonDatas[i]);
	});
	jsonDatas=arr;
	console.log('select',nums,index,jsonDatas)
	selectSound(false);
}
var bg=getUrlVar('bg');
if(bg) document.body.style.backgroundImage=`url(${bg})`;
var color=getUrlVar('color');
if(color) changeColor(color)

function changeColor(color){
	labelName.color=color;
	labelLyrics.color=color;
	labelTime.color=color;
}